<!DOCTYPE html>
<html>
  <head>
    <title>User Management</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css"
    />
    <style>
      body {
        font-family: Arial, sans-serif;
        background-color: #f0f0f0;
        margin: 0;
        padding: 0;
      }
      .container {
        max-width: 600px;
        margin: 0 auto;
        background-color: #fff;
        padding: 20px;
        border-radius: 5px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      }
      .form-group {
        margin-bottom: 15px;
      }
      label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
      }
      input[type="text"],
      input[type="email"],
      input[type="password"],
      textarea {
        width: calc(100% - 20px);
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 3px;
      }
      textarea {
        resize: vertical;
      }
      button {
        padding: 10px 15px;
        background-color: #007bff;
        color: #fff;
        border: none;
        border-radius: 3px;
        cursor: pointer;
      }
      button:hover {
        background-color: #0056b3;
      }
      button + button {
        margin-left: 10px;
      }
      .user-card {
        border: 1px solid #ccc;
        padding: 10px;
        margin-bottom: 10px;
      }
      .user-card h3 {
        margin-top: 0;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>User Management</h1>
      <h3>node-express-sequelize-mysql</h3>
      <h2>Create User</h2>
      <form id="create-user-form">
        <div class="form-group">
          <label for="username">Username:</label>
          <input type="text" id="username" required />
        </div>
        <div class="form-group">
          <label for="email">Email:</label>
          <input type="email" id="email" required />
        </div>
        <div class="form-group">
          <label for="password">Password:</label>
          <input type="password" id="password" required />
        </div>
        <div class="form-group">
          <label for="fullName">Full Name:</label>
          <input type="text" id="fullName" required />
        </div>
        <div class="form-group">
          <label for="bio">Bio:</label>
          <textarea id="bio"></textarea>
        </div>
        <button type="submit">Create User</button>
      </form>

      <h2>Users List</h2>
      <div id="users-list"></div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <script>
      // Helper function to make API requests
      async function makeRequest(url, method, data) {
        const response = await fetch(url, {
          method: method,
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        });

        if (!response.ok) {
          throw new Error("Network response was not ok");
        }

        return response.json();
      }

      // Function to fetch all users from the server and display them
      // async function fetchAndDisplayUsers() {
      //   try {
      //     const usersListElement = document.getElementById("users-list");
      //     usersListElement.innerHTML = "";

      //     const users = await makeRequest("/users", "GET");

      //     users.forEach((user) => {
      //       const userCard = document.createElement("div");
      //       userCard.classList.add("user-card");

      //       const heading = document.createElement("h3");
      //       heading.textContent = user.username;
      //       userCard.appendChild(heading);

      //       const email = document.createElement("p");
      //       email.textContent = `Email: ${user.email}`;
      //       userCard.appendChild(email);

      //       const fullName = document.createElement("p");
      //       fullName.textContent = `Full Name: ${user.fullName}`;
      //       userCard.appendChild(fullName);

      //       const bio = document.createElement("p");
      //       bio.textContent = `Bio: ${user.bio || "N/A"}`;
      //       userCard.appendChild(bio);

      //       usersListElement.appendChild(userCard);
      //     });
      //   } catch (error) {
      //     console.error("Error fetching users:", error.message);
      //   }
      // }

      async function fetchAndDisplayUsers() {
        try {
          const usersListElement = document.getElementById("users-list");
          usersListElement.innerHTML = "";

          const users = await makeRequest("/users", "GET");

          users.forEach((user) => {
            const userCardWithActions = displayUserCardWithActions(user);
            usersListElement.appendChild(userCardWithActions);
          });
        } catch (error) {
          console.error("Error fetching users:", error.message);
          Toastify({
            text: error.message,
            duration: 3000, // 3 seconds
            // close: true,
            gravity: "top", // Position of the toast notification
            position: "center",
            backgroundColor: "#f00",
            stopOnFocus: true,
          }).showToast();
        }
      }

      // Event listener for the "Create User" form
      document
        .getElementById("create-user-form")
        .addEventListener("submit", async (event) => {
          event.preventDefault();

          const userData = {
            username: document.getElementById("username").value,
            email: document.getElementById("email").value,
            password: document.getElementById("password").value,
            fullName: document.getElementById("fullName").value,
            bio: document.getElementById("bio").value,
          };

          try {
            await makeRequest("/users", "POST", userData);
            // alert("User created successfully!");
            Toastify({
              text: "User created successfully!",
              duration: 3000, // 3 seconds
              // close: true,
              gravity: "top", // Position of the toast notification
              position: "center",
              backgroundColor: "#007bff",
              stopOnFocus: true,
            }).showToast();

            fetchAndDisplayUsers(); // Refresh the list of users
          } catch (error) {
            console.error("Error creating user:", error.message);
            Toastify({
              text: error.message,
              duration: 3000, // 3 seconds
              // close: true,
              gravity: "top", // Position of the toast notification
              position: "center",
              backgroundColor: "#f00",
              stopOnFocus: true,
            }).showToast();
          }
        });

      // Function to handle user deletion
      async function deleteUser(uuid) {
        try {
          await makeRequest(`/users/${uuid}`, "DELETE");
          // alert("User deleted successfully!");
          Toastify({
            text: "User deleted successfully!",
            duration: 3000, // 3 seconds
            // close: true,
            gravity: "top", // Position of the toast notification
            position: "center",
            backgroundColor: "#007bff",
            stopOnFocus: true,
          }).showToast();
          fetchAndDisplayUsers(); // Refresh the list of users
        } catch (error) {
          console.error("Error deleting user:", error.message);

          Toastify({
            text: error.message,
            duration: 3000, // 3 seconds
            // close: true,
            gravity: "top", // Position of the toast notification
            position: "center",
            backgroundColor: "#f00",
            stopOnFocus: true,
          }).showToast();
        }
      }

      // Function to handle user update
      async function updateUser(uuid, updatedUserData) {
        try {
          await makeRequest(`/users/${uuid}`, "PUT", updatedUserData);
          // alert("User updated successfully!");
          Toastify({
            text: "User updated successfully!",
            duration: 3000, // 3 seconds
            // close: true,
            gravity: "top", // Position of the toast notification
            position: "center",
            backgroundColor: "#007bff",
            stopOnFocus: true,
          }).showToast();
          fetchAndDisplayUsers(); // Refresh the list of users
        } catch (error) {
          console.error("Error updating user:", error.message);

          Toastify({
            text: error.message,
            duration: 3000, // 3 seconds
            // close: true,
            gravity: "top", // Position of the toast notification
            position: "center",
            backgroundColor: "#f00",
            stopOnFocus: true,
          }).showToast();
        }
      }

      // Function to display the update form
      function showUpdateForm(user) {
        const updateForm = document.createElement("form");
        updateForm.innerHTML = `
          <div class="form-group">
            <label for="username">Username:</label>
            <input type="text" id="update-username" value="${
              user.username
            }" required />
          </div>
          <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="update-email" value="${
              user.email
            }" required />
          </div>
          <div class="form-group">
            <label for="fullName">Full Name:</label>
            <input type="text" id="update-fullName" value="${
              user.fullName
            }" required />
          </div>
          <div class="form-group">
            <label for="bio">Bio:</label>
            <textarea id="update-bio">${user.bio || ""}</textarea>
          </div>
          <button type="submit">Update User</button>
          <button type="button" onclick="cancelUpdate()">Cancel</button>
        `;

        updateForm.addEventListener("submit", async (event) => {
          event.preventDefault();

          const updatedUserData = {
            username: document.getElementById("update-username").value,
            email: document.getElementById("update-email").value,
            fullName: document.getElementById("update-fullName").value,
            bio: document.getElementById("update-bio").value,
          };

          updateUser(user.uuid, updatedUserData);
        });

        const userCard = document.getElementById(`user-card-${user.uuid}`);
        userCard.innerHTML = ""; // Clear existing content
        userCard.appendChild(updateForm);
      }

      // Function to cancel the update form and display user details again
      function cancelUpdate() {
        fetchAndDisplayUsers(); // Refresh the list of users
      }

      // Function to display the user card with update and delete buttons
      function displayUserCardWithActions(user) {
        const userCard = document.createElement("div");
        userCard.id = `user-card-${user.uuid}`;
        userCard.classList.add("user-card");

        const heading = document.createElement("h3");
        heading.textContent = user.username;
        userCard.appendChild(heading);

        const email = document.createElement("p");
        email.textContent = `Email: ${user.email}`;
        userCard.appendChild(email);

        const fullName = document.createElement("p");
        fullName.textContent = `Full Name: ${user.fullName}`;
        userCard.appendChild(fullName);

        const bio = document.createElement("p");
        bio.textContent = `Bio: ${user.bio || "N/A"}`;
        userCard.appendChild(bio);

        // Update button
        const updateButton = document.createElement("button");
        updateButton.textContent = "Update";
        updateButton.addEventListener("click", () => showUpdateForm(user));
        userCard.appendChild(updateButton);

        // Delete button
        const deleteButton = document.createElement("button");
        deleteButton.textContent = "Delete";
        deleteButton.addEventListener("click", () => deleteUser(user.uuid));
        userCard.appendChild(deleteButton);

        return userCard;
      }

      // Fetch and display users when the page loads
      fetchAndDisplayUsers();
    </script>
  </body>
</html>
